// ==UserScript==
// @name         happy，塞大声望了
// @namespace    http://tampermonkey.net/
// @version      1.14.4
// @description  去码头整点声望
// @author       fc
// @updateURL    https://gitee.com/fcgiteeeee/note/raw/master/Ascript.js
// @downloadURL  https://gitee.com/fcgiteeeee/note/raw/master/Ascript.js
// @match        https://bbs.nga.cn/nuke.php?func=message*
// @match        https://bbs.nga.cn/read.php?tid=*
// @match        https://bbs.nga.cn/thread.php*
// @match        https://ngabbs.com/nuke.php?func=message*
// @match        https://ngabbs.com/read.php?tid=*
// @match        https://ngabbs.com/thread.php*
// @require      https://raw.githubusercontent.com/turuslan/HackTimer/master/HackTimer.js
// @require      https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js
// @require      https://gitee.com/fcgiteeeee/note/raw/f9283e9b0a3437709570e3168900a56984446851/waitForKeyElements.js
// @require      https://blog.whyoop.com/GBK.js/dist/gbk.js
// @require      https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js
// @require      https://unpkg.com/element-ui/lib/index.js
// @resource     ELEMENT_UI    https://unpkg.com/element-ui/lib/theme-chalk/index.css
// @grant        GM_getResourceText
// @grant        GM_addStyle
// @grant        GM_setClipboard
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_listValues
// ==/UserScript==

(function () {
    'use strict';
    let nanoid = (t = 21) => { let e = "", r = crypto.getRandomValues(new Uint8Array(t)); for (; t--;) { let n = 63 & r[t]; e += n < 36 ? n.toString(36) : n < 62 ? (n - 26).toString(36).toUpperCase() : n < 63 ? "_" : "-" } return e };
    const ELEMENT_UI = GM_getResourceText("ELEMENT_UI");
    GM_addStyle(ELEMENT_UI);

    const potentialBG = "rgb(64, 187, 96)";//无A版声望用户颜色-绿色
    const prePostedBG = "rgb(91, 175, 224)";//有A版声望但未发帖用户颜色-蓝色
    const banishBG = "rgb(210, 93, 104)";//A版声望低于0用户颜色-红色
    const postedBG = "rgb(236, 209, 12)";//已在A版发帖用户颜色-金色
    const inlineButtonSuccessBG = "rgb(41, 253, 48)"
    var pagePropSwitch = false;
    let nodeArray = [];
    let postRowObserver={};

    $("body").append('<div id="vueroot"></div>');
    const vm = new Vue({
        el: "#vueroot",
        template: `
        <div>
        <el-dialog title="" :visible.sync="botDialogVisible" :close-on-click-modal="false" :show-close="false">
        <h1 style="text-align: center">机器人工作中...</h1>
        <h2 style="text-align: center">要停止，请刷新或关闭页面</h2>
        <h2></br></h2>
        </el-dialog>
        <el-dialog title="" :visible.sync="gambleDialogVisible" :close-on-click-modal="false" :show-close="false">
        <h1 style="text-align: center">自动扣除菠菜声望中...</h1>
        <h2 style="text-align: center">要停止，请刷新或关闭页面</h2>
        <el-progress :percentage="gambleBotPercentage"></el-progress>
        <h2></br></h2>
        </el-dialog>
        <el-dialog
        title="版务声望脚本设置"
        :visible.sync="dialogVisible"
        :before-close = "handleClose"
        :close-on-click-modal = "false"
        width="860px" >
        <el-tooltip content="123123" placement="left-start">
        <span><h3>无声望用户默认发放声望</h3></span>
        </el-tooltip>
        <el-input v-model="config.repSetTo" placeholder="请输入内容"></el-input>
        </br></br>
        <hr/>

        <h3>“快速评分操作”配置</h3>
        <ul style="list-style-type:none">
        <li>
        <el-row :gutter="20" v-show="config.postDefault.length">
        <el-col :span="8" style="text-align:center" ><h4>显示提示</h4></el-col><el-col :span="4" style="text-align:center"><h4>声望操作量</h4></el-col><el-col :span="8" style="text-align:center"><h4>操作留言提示</h4></el-col>
        </el-row>
        </li>
        <li v-for="repSetObj in config.postDefault" :key="repSetObj.id">
        <el-row :gutter="20">
        <el-col :span="8"><el-input v-model="repSetObj.name" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="4"><el-input v-model="repSetObj.repPoint" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="8"><el-input v-model="repSetObj.info" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="2"><el-button type="danger" @click="deleteRepSetObj(repSetObj.id)">删除</el-button></el-col>
        </el-row>
        </li>
        </ul>
        <el-button type="success" @click="addRepSetObj">添加新“快速评分操作”配置项</el-button>
        </br></br><hr/>

        <span><h3>“声望菠菜”设置</h3></span>
        <el-switch  v-model="config.gamblingSwitch"  active-text="菠菜回复检测"></el-switch>
        </br></br>
        <div v-for="winObj in config.gamblePresets">
        <el-card class="box-card" >
        <div slot="header" class="clearfix">
        <el-row :gutter="20">
        <el-col :span="4" style="text-align:center"><h4>投注项名称：</h4></el-col>
        <el-col :span="6" ><el-input v-model="winObj.winner" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="2" style="text-align:center"><h4>赔率：</h4></el-col>
        <el-col :span="4" ><el-input v-model="winObj.betRatio" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="2" :offset="4"><el-button type="danger" @click="deleteWinObj(winObj.id)">删除</el-button></el-col>
        </el-row>
        </div>
        <span><h4>&nbsp;&nbsp;&nbsp;匹配字符串：</h4></span>
        <el-row v-for="searchStr in winObj.searchStrs">
        <el-col :span="8" :offset="1"><el-input v-model="searchStr.str" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="4" :offset="1"><el-button type="danger" @click="deleteSearchStr(winObj.id,searchStr.id)">删除</el-button></el-col>
        </el-row>
        <el-row><el-col :offset="1"><el-button type="success" @click="addSearchStr(winObj.id)">添加新匹配字符串</el-button></el-col></el-row>
        </el-card>
        </br>
        </div>
        <el-button type="success" @click="addWinObj">添加新“投注项”配置项</el-button>
        </br></br><hr/>

        <span><h3>“声望查询自动回复”设置</h3></span>
        <el-row :gutter="0">
        <el-col :span="7" style="text-align:center"><h4>评论间隔（不低于2000毫秒）：</h4></el-col>
        <el-col :span="4"><el-input v-model="config.waitTime" placeholder="请输入内容"></el-input></el-col>
        <el-col :span="9" style="text-align:center"><h4>页面刷新最短时长（不低于两倍评论间隔）：</h4></el-col>
        <el-col :span="4"><el-input v-model="config.pageReloadMinTime" placeholder="请输入内容"></el-input></el-col>
        </el-row>
        <el-button type="success" @click="startPagePropagation">开启自动回复-查询声望</el-button>
        </br></br>
        <hr/>

        <span><h3>杂项</h3></span>
        <el-switch  v-model="config.ratingCalculateSwitch"  active-text="评分贴自动计算总分"></el-switch>


        <span slot="footer" class="dialog-footer">
        <span>保存后记得刷新一下网页</span>
        <el-button type="primary" @click="saveConfig">保 存</el-button>
        </span>
        </el-dialog>
        </div>`,
        data() {
            return {
                hello: "HelloWorld",
                dialogVisible: false,
                botDialogVisible: false,
                gambleDialogVisible: false,
                gambleBotPercentage: 0,
                config: {
                    ratingCalculateSwitch: false,
                    waitTime: 2000,
                    pageReloadMinTime: 10000,
                    repSetTo: 1,
                    postDefault: [
                        {
                            id: 1,
                            name: "普通奖励",
                            repPoint: "+15",
                            info: "好",
                        },
                        {
                            id: 2,
                            name: "更多奖励",
                            repPoint: "+30",
                            info: "好上好",
                        },
                        {
                            id: 3,
                            name: "普通处罚",
                            repPoint: "-15",
                            info: "不彳亍",
                        },
                    ],
                    gamblingSwitch: true,
                    gamblePresets: [
                        {
                            id: 1,
                            winner: "贝拉",
                            searchStrs: [{
                                id: 1,
                                str: "贝拉"
                            },
                            {
                                id: 2,
                                str: "拉姐"
                            },
                            {
                                id: 3,
                                str: "大聪明"
                            },],
                            betRatio: 1.7,
                        },
                        {
                            id: 2,
                            winner: "嘉然",
                            searchStrs: [{
                                id: 1,
                                str: "嘉然"
                            },
                            {
                                id: 2,
                                str: "然然"
                            },
                            {
                                id: 3,
                                str: "粉色小矮子"
                            },],
                            betRatio: 1.6,
                        },
                    ],
                },
            }
        },
        methods: {
            handleClose() {
                this.$confirm('是否保存？')
                    .then(_ => {
                        this.saveConfig();
                    })
                    .catch(_ => {
                        this.dialogVisible = false;
                    });
            },
            saveConfig() {
                GM_setValue("config", this.config);
                this.dialogVisible = false;
            },
            showDialog() {
                this.dialogVisible = true;
            },
            deleteRepSetObj(id) {
                this.config.postDefault = this.config.postDefault.filter((a) => (a.id !== id));
            },
            deleteWinObj(id) {
                this.config.gamblePresets = this.config.gamblePresets.filter((a) => (a.id !== id));
            },
            deleteSearchStr(id, strId) {
                var index = this.config.gamblePresets.findIndex((a) => (a.id == id));
                this.config.gamblePresets[index].searchStrs = this.config.gamblePresets[index].searchStrs.filter((a) => (a.id !== strId));
                // console.log(this.config.gamblePresets[index].searchStrs)
            },
            addRepSetObj() {
                var newRepSetObj = {
                    id: nanoid(),
                    name: "请填写内容",
                    repPoint: "+1",
                    info: "请填写内容",
                }
                this.config.postDefault.push(newRepSetObj);
            },
            addWinObj() {
                var newWinObj = {
                    id: nanoid(),
                    winner: "请输入内容",
                    searchStrs: [
                        {
                            id: nanoid(),
                            str: "请输入内容"
                        },
                    ],
                    betRatio: 2,
                }
                this.config.gamblePresets.push(newWinObj);
            },
            addSearchStr(id) {
                var newSearchStr = {
                    id: nanoid(),
                    str: "请输入内容"
                }
                // console.log(id)
                var index = this.config.gamblePresets.findIndex((a) => (a.id == id));
                this.config.gamblePresets[index].searchStrs.push(newSearchStr);
            },
            startPagePropagation() {//开启页面迭代，设置迭代开关为true，进行一次页面处理（此处是自动声望回复处理）
                pagePropSwitch = true;
                this.dialogVisible = false;
                this.botDialogVisible = true;
                autoRepComment();
            },
        },
        mounted() {
            var oldConfig = GM_getValue("config");
            if (oldConfig === undefined) {
                GM_setValue("config", this.config);
            } else {
                var newConfigKeys = Object.keys(this.config);
                var setOld = new Set(Object.keys(oldConfig));
                var toBeUpdateKeys = newConfigKeys.filter(a => !setOld.has(a))
                if (toBeUpdateKeys.length != 0) {
                    var that = this;
                    toBeUpdateKeys.forEach(function (key) {
                        oldConfig[key] = that.config[key];
                    })
                }
                this.config = oldConfig;
            }
        },
    })
    $('[title="APP下载"]').parent().parent().append($('[title="APP下载"]').parent().clone().attr("id", "scriptConfig"))
    $('#scriptConfig').children().text("版务声望脚本设置").click(function (e) {
        vm.showDialog();
        e.preventDefault();
    });

    waitForKeyElements("a.from:not(.silver)", messageFun);
    waitForKeyElements("#m_posts_c", pageLoaded);



    function pageLoaded() {
        postRowObserver = new MutationObserver(pageAjaxLoadedAnotherPage);
        postRowObserver.observe(document.getElementById('m_posts_c'),{childList:true,});
        nodeArray = nodeAssemble();
        nodeArray.forEach(function (nodeObj) {//对每一个node调用老版本的threadFun
            threadFun(nodeObj);
        })
        if (vm.config.ratingCalculateSwitch) {
            ratingPostCalculate(nodeArray);
        }
        if (__CURRENT_FID === -5944654 && vm.config.gamblingSwitch) {
            $('[title="发表回复"]:first').parent().parent().prepend($('[title="发表回复"]:first').parent().clone(false).attr("id", "pageGambleBetCollect"))
            $("#pageGambleBetCollect").children().children().css("color", "#f92c52").text("菠菜—收取本页投注");
            $("#pageGambleBetCollect").click(pageGambleBetCollect)
        }
        //处理前后翻页键
        // $('[title="加载上一页"]').parent().css("display", "none");
        // $('[title="加载下一页"]').parent().css("display", "none");
        if (pagePropSwitch) {//如果迭代开关为1，进行页面处理
            autoRepComment();
        }
    }

    function pageAjaxLoadedAnotherPage(){
        console.log("@@pageAjaxLoadedAnotherPage");
        let oldFloorSet = new Set(nodeArray.map(item=>item.floor));
        let newNodeArray = nodeAssemble()
        let recentlyAddedNodeArray = newNodeArray.filter(x=>!oldFloorSet.has(x.floor));
        recentlyAddedNodeArray.forEach(function(nodeObj){
            threadFun(nodeObj);
        });
        nodeArray = newNodeArray;
    }

    function ratingPostCalculate(nodeArray) {
        let tableNode = null;
        nodeArray.filter(a => a.floor == 0).forEach(a => tableNode = a.postrowNode.find('table[id^="vote"]').children().children());
        if (tableNode) {
            let rateCountArray = [];
            tableNode.children(':nth-child(3)').each(function () {
                rateCountArray.push($(this).text());
            });
            rateCountArray = rateCountArray.map(a => +a.match(/\d+/)[0]);
            let rate = rateCountArray.map((count, index) => (count * (index + 5))).reduce((accu, value) => (accu + value), 0) / rateCountArray.reduce((accu, value) => (accu + value), 0);
            rate = rate.toFixed(2);
            tableNode.parent().parent().after(`<span style="color:red">最终得分：${rate}</span>`);
        }
    }

    function autoRepComment() {//页面处理，全部处理完毕后，进入下一页
        var pageReloadMinTime = vm.config.pageReloadMinTime;
        var waitTime = vm.config.waitTime;
        var toCommentCount = 1;
        for (var i = 0, j = nodeArray.length; i < j; i++) {
            var node = nodeArray[i]
            if (node.floor != "0" && node.postContent.includes("声望") && !node.commentFlag && !(node.comment.join("").includes("您当前声望为"))) {
                (function (index, toCommentCount) {
                    setTimeout(function () {
                        comment(nodeArray[index], "您当前声望为" + nodeArray[index].reputation);
                        console.log("@@" + nodeArray[index].floor + "楼   内容:" + nodeArray[index].postContent + "  自动评论:您当前声望为" + nodeArray[index].reputation)
                    }, toCommentCount * waitTime);
                })(i, toCommentCount);
                toCommentCount++;
            }
        }
        setTimeout(nextPage, toCommentCount * waitTime < pageReloadMinTime ? pageReloadMinTime : toCommentCount * waitTime)
    }

    function comment(nodeObj, comment) {
        if (nodeObj.commentFlag)
            return false;
        if (nodeObj.pid == 0) {
            $.post("post.php", 'action=reply&fid=' + __CURRENT_FID + '&tid=' + __CURRENT_TID + '&post_content=' + GBK.URI.encodeURI(comment) + '&comment=1&nojump=1&lite=htmljs&step=2')
        }
        else {
            $.post("post.php", 'action=reply&fid=' + __CURRENT_FID + '&tid=' + __CURRENT_TID + '&pid=' + nodeObj.pid + '&post_content=' + GBK.URI.encodeURI(comment) + '&comment=1&nojump=1&lite=htmljs&step=2')
        }

        return true;
    }

    function nextPage() {
        if ($("#pagebtop").find(".invert").parent().next().children().attr("name") == "topage")
            $("#pagebtop").find(".invert")[0].click();
        else {
            $("#pagebtop").find(".invert").parent().next().children().attr("tag", "tagd")[0].click();
        }
    }

    function nodeAssemble() {
        let nodeArray = [];
        $(".postrow").each(function () {
            nodeArray.push({
                postrowNode: $(this),
                uidNode: $(this).find('[name="uid"]'),
                uid: $(this).find('[name="uid"]').text(),
                comment: Array.from($(this).find("[id^=postcomment_]"), (a) => a.innerText),
                pid: $(this).children(".c2:first").children().first().attr("id").replace("pid", "").replace("Anchor", ""),
                commentFlag: $(this).find('[title="这是对某一个帖子的评论/回复/贴条"]').length == 1,
                postContent: getOwnText($(this).find(".postcontent:first")[0]),
                reputation: $(this).find(".silver.numericl:first")[0].innerText.match(/\d+/)[0],
                floor: $(this).attr("id").match(/strow\d+/)[0].match(/\d+/)[0],
                score: $(this).find("#alertc" + $(this).attr("id").match(/strow\d+/)[0].match(/\d+/)[0]).children().text(),
            });
            // var that = nodeArray[nodeArray.length-1];
            // console.log("@",that.floor,"   socre:",that.score);
        })

        return nodeArray
    }


    function threadFun(nodeObj) {
        let jNode = nodeObj.uidNode;
        if (__CURRENT_FID === -5944654) {
            //当前处于A版
            var c2 = jNode.parents(".c1").next();
            var floor = c2.attr("id").match(/\d+/);
            var pid = c2.children().first().attr("id").replace("pid", "").replace("Anchor", "");
            for (var setting in vm.config.postDefault) {
                var repPrepSet = $('<span class="block_txt block_txt_c2" style="margin-bottom:0.25em;margin-right:1em;cursor:pointer;background:#ffdd8e" RAValue="' + vm.config.postDefault[setting].repPoint + '" RAInfo="' + vm.config.postDefault[setting].info + '"><span class="block_txt block_txt_c0" style="margin-left:-0.4em;background:#e0c19e">☆</span> ' + vm.config.postDefault[setting].name + '</span>');
                if (vm.config.postDefault[setting].repPoint[0] === '+' || vm.config.postDefault[setting].repPoint[0] === '-') {
                    repPrepSet.one('click', function () {
                        repAdd2(__CURRENT_TID,
                            pid,
                            this.getAttribute('RAValue'),
                            this.getAttribute('RAInfo')
                        ).then(() => {
                            this.style.backgroundColor = inlineButtonSuccessBG;
                        }).catch((err) => {
                            alert(err);
                        });
                        //console.log(__CURRENT_TID,pid,this.getAttribute('RAValue'),GBK.URI.encodeURI(this.getAttribute('RAInfo')),function(){})
                    })
                }
                else {
                    repPrepSet.one('click', async function () {
                        if (await repAddTo2(jNode.text(), __CURRENT_TID, pid, this.getAttribute('RAValue'), this.getAttribute('RAInfo'))) {
                            this.style.backgroundColor = inlineButtonSuccessBG;
                        }
                        //console.log(jNode.text(),__CURRENT_TID,pid,this.getAttribute('RAValue'),GBK.URI.encodeURI(this.getAttribute('RAInfo')),function(){})
                    })
                }
                c2.append(repPrepSet);
            }
            c2.append("</br></br>");
            if (vm.config.gamblingSwitch) {
                var postContent = nodeObj.postContent;
                var regBet = postContent.match(/\d+声望/);
                if (regBet === null) regBet = postContent.match(/投注量\d+/);
                if (regBet === null) regBet = postContent.match(/投注\d+/);
                if (regBet != null && floor != 0) {
                    regBet = regBet[0].match(/\d+/);
                    regBet = regBet[0];
                    var collect = $('<span class="block_txt block_txt_c2 regBetCollect" style="margin-bottom:0.25em;margin-right:1em;cursor:pointer;background:#f99393" regBet="' + regBet + '"><span class="block_txt block_txt_c0" style="margin-left:-0.4em;background:#c32121">↓</span> ' + "收取投注声望：" + regBet + '</span>');
                    collect.one("click", function () {
                        collectBet(jNode.text(), __CURRENT_TID, pid, this.getAttribute('regBet')).then(() => {
                            this.style.backgroundColor = inlineButtonSuccessBG;
                        });
                    })
                    c2.append(collect);

                    var alerts = c2.find("#alertc" + floor).children().text();
                    if (alerts.match(/收您\d+枚筹码/) != null) regBet = Number(alerts.match(/收您\d+枚筹码/)[0].match(/\d+/));
                    for (var preset in vm.config.gamblePresets) {

                        var maKeys = vm.config.gamblePresets[preset].searchStrs;
                        console.dir(maKeys)
                        var withdrawRep = Number(regBet) * vm.config.gamblePresets[preset].betRatio;
                        withdrawRep = parseInt(withdrawRep);
                        var hitFlag = false;
                        for (var i in maKeys) {
                            if (postContent.includes(maKeys[i].str)) {
                                hitFlag = true;
                            }
                        }
                        if (hitFlag&&alerts.match(/收您\d+枚筹码/)) {
                            var withdraw = $('<span class="block_txt block_txt_c2" style="margin-bottom:0.25em;margin-right:1em;cursor:pointer;background:#DCE775;color:#000000" withdrawRep="' +
                                withdrawRep + '"><span class="block_txt block_txt_c0" style="margin-left:-0.4em;background:#24c321">✔</span> 投注:' +
                                vm.config.gamblePresets[preset].winner + " " + regBet + "声望 赔率" + vm.config.gamblePresets[preset].betRatio + " 赢回" + withdrawRep + '声望</span>');
                            withdraw.one('click', async function () {
                                repAdd2(__CURRENT_TID, pid, this.getAttribute('withdrawRep'), "恭喜您获得胜利,请收好筹码").then(() => {
                                    this.style.backgroundColor = inlineButtonSuccessBG;
                                });
                            });
                            c2.append(withdraw)
                        }
                    }
                }

            }
            var voter = c2.find("#postsubject" + floor).prevAll("span.stxt").children("span.white");
            voter.text(
                voter.attr("title").replace("支持 ", "/").replace("反对 (版主可见)", "")
            );
        }

        if (GM_getValue(jNode.text(), "null") == "posted") {
            jNode.css("background-color", postedBG);
        }
        //jNode.unbind("click");
        jNode.click(async function (event) {
            //console.log(jNode.css("background-color"))
            if (jNode.css("background-color") == "rgb(170, 170, 170)") {
                let rep = await repCheck2(jNode.text());
                if (rep > 0) {
                    threadCheck(jNode.text(), function (res) {
                        if (res) {
                            jNode.css("background-color", prePostedBG);
                            atToClip(jNode.prev().text());
                        }
                        else {
                            jNode.css("background-color", postedBG);
                            GM_setValue(jNode.text(), "posted");
                        }
                    });
                }
                if (rep == 0) {
                    jNode.css("background-color", potentialBG);
                }
                if (rep < 0) {
                    jNode.css("background-color", banishBG);
                }
            }
            else if (jNode.css("background-color") == potentialBG) {
                repSet(jNode.text(), function () {
                    atToClip(jNode.prev().text());
                });
            }
        });
    }

    function messageFun(jNode) {
        jNode.after("<a style=\"color:red;cursor:pointer\"> 给他塞点声望</a>");
        jNode.next().click(async function (event) {
            var re = new RegExp("\\d{2,}");
            var id = re.exec($(event.target).prev().attr("href"));
            if (id) {
                let repu = await repCheck2(id);
                if (repu == 0) {
                    repSet(id, function () { });
                }
                else {
                    alert("该用户声望不为0");
                }
            }
            else {
                alert("这人好像没有id，你不会是在给#SYSTEM#塞声望吧？")
            }
        });
    };

    function threadCheck(tarId, cb) {
        $.post("thread.php?searchpost=1&authorid=" + tarId + "&fid=-5944654", function (data) {
            var re = new RegExp("<title>没有符合条件的结果</title>");
            var res = re.exec(data);
            cb(res);
        });
    }

    async function repCheck2(tarId) {
        let response = await fetch(`nuke.php?func=user_reputation&uid=${tarId}`, {
            method: "POST",
            headers: { 'content-type': 'application/x-www-form-urlencoded', },
            body: `nameselect=uid&name=5944654`
        })
        if (response.ok) {
            let responseHtml = await utf8BlobToGBKString(await response.blob());
            let res = Number(responseHtml.match(/的声望为 (-?\w+)/)?.[1]);
            if (res === NaN) {
                throw new Error("网络连接正常，但未查询到声望，是否查询了匿名用户的声望？");
            }
            return res;
        }
        else {
            throw new Error(`声望查询失败 HTML响应：${response.status}`);
        }
    }

    async function utf8BlobToGBKString(blob) {
        try {
            let promise = new Promise(function (resolve, reject) {
                let reader = new FileReader();
                reader.readAsText(blob, 'GBK');
                reader.onload = function () {
                    resolve(reader.result);
                };
                reader.onerror = function () {
                    reject(reader.error);
                }
            });
            return promise;
        }
        catch (e) {
            throw e;
        }

    }


    function atToClip(tarName) {
        var s = new String();
        s = s.concat("[@");
        s = s.concat(tarName);
        s = s.concat("]");
        //console.log(s)
        GM_setClipboard(s);
    }

    function repSet(tarId, cb) {
        $.post("nuke.php?__lib=user_reputation&__act=set&raw=3", "user=" + tarId + "&fid=-5944654&value=" + vm.config.repSetTo, function (data) {
            var repResRe = new RegExp("\{.+\{\"0\":.+\}.+\}");
            var res = repResRe.exec(String(data));
            res = JSON.parse(res);
            if (res.error) {
                alert(String(res.error[0]));
            }
            if (res.data) {
                alert(String(res.data[0]));
            }
            cb();
        });
    }

    async function repAdd2(tid, pid, value, info) {
        try {
            let response = await fetch("nuke.php", {
                method: "POST",
                headers: { 'content-type': 'application/x-www-form-urlencoded', },
                body: `__lib=add_point_v3&__act=add&opt=4194336&fid=-5944654&tid=${tid}&pid=${pid}&info=${GBK.URI.encodeURI(info)}&value=${value}&raw=3`
            })
            if (response.ok) {
                let responseHtml = await utf8BlobToGBKString(await response.blob())
                let res = JSON.parse(/{.+{"0":.+}.+}/.exec(responseHtml));
                if (res.error) {
                    throw new Error("网络正常，NGA返回错误：" + res.error[0] + "若错误为“参数错误”，请确认是否尝试评0分，这通常发生在通过评分将声望设置为此层主当前声望时")
                }
                if (res.data) {
                    return;
                }
            }
            else {
                throw new Error(`声望增加失败 HTML响应：${response.status}`)
            }
        }
        catch(e){
            alert(e);
        }
    }

    async function repAddTo2(tarId, tid, pid, addToValue, info) {
        let oldRep = await repCheck2(tarId)
        if (await repAdd2(tid, pid, addToValue - oldRep, info)) {
            return true;
        }
    }

    function pageGambleBetCollect(e) {
        e.preventDefault();
        if (confirm("确定要对这一页进行自动投注扣除吗？")) {
            vm.gambleDialogVisible = true;
            $(".regBetCollect").each(function (i, node) {
                setTimeout(function () {
                    node.click();
                    vm.gambleBotPercentage = 100 * (i + 1) / $(".regBetCollect").length;
                }, i * 1000)
            });
            setTimeout(function () {
                vm.gambleDialogVisible = false;
            }, ($(".regBetCollect").length - 1) * 1000);

        }
    }

    async function collectBet(tarId, tid, pid, betCost) {
        let oldRep = await repCheck2(tarId);
        if (oldRep < 1) {
            alert("该用户声望低于1");
        }
        else if (oldRep == 1) {
            await repAdd2(tid, pid, 1, "阁下似乎筹码不足呢");
            await new Promise(resolve => setTimeout(() => resolve(), 1000));
            await repAdd2(tid, pid, -1, "还请领取筹码后再来");
        }
        else if (oldRep - 1 < betCost) {
            await repAdd2(tid, pid, 1 - oldRep, "收您" + (oldRep - 1) + "枚筹码,欢迎来到DDZ");
        }
        else {
            await repAdd2(tid, pid, 0 - betCost, "收您" + betCost + "枚筹码,欢迎来到DDZ");
        }
    }

    function getOwnText(domNode) {
        var arr = [];
        for (var i = 0, len = domNode.childNodes.length; i < len; i++) {
            if (domNode.childNodes[i].nodeType === 3) {  // 通过nodeType是不是文本节点来判断
                arr.push(domNode.childNodes[i].nodeValue);
            }
        }
        var str = arr.join("");
        return str;
    }
})();